/*
 * @Author: yangzonglong
 * @Date: 2020-07-15 09:40:52
 * @version: v1.0.0
 * @Descripttion: 替换对象中指定格式的文本
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-02-25 15:26:17
 * @Auditor: 
 */
import { stringify, parse } from './../json/json';

export function eachStr(str: string, callback: Function) {
  return str.replace(new RegExp('\\{{(.*?)\\}}','g'), (item: string) => {
    const k = item.match(new RegExp('{{(\\S*)}}'))?.[1];
    return callback(k as string)
  })
}

export function replaceObj(target: string | object, data: object | undefined | null) {
  if (!data) return {};

  let jsonStr = typeof target === 'string' ? target : stringify(target);
  jsonStr = eachStr(jsonStr, (k: string) => data[k]);

  return parse(jsonStr)
}

export function parsingStr(str: string, data: object | undefined | null, callback?: Function) {
  const _data = data || {};
  return eachStr(str, (k: string) => {
    callback?.(k);

    if(typeof _data[k!] === 'string') return `"${_data[k!]}"`;

    // dayjs
    if(_data[k!]?.format) return `"${_data[k!]}"`;

    return _data[k!]
  })
}